package com.hand.exam.controller;

import com.hand.exam.annoction.TestAnnoction;
import com.hand.exam.domain.Matter;
import com.hand.exam.domain.Mattersave;
import com.hand.exam.service.IMatterService;
import com.hand.exam.service.IMattersaveService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 马旭阳
 * @date2019/7/20
 */
@RestController
@RequestMapping(value = "/mattersave")
public class MattersaveController {
    @Autowired
    private IMatterService matterService;
    @Autowired
    private IMattersaveService mattersaveService;

    @PostMapping(value = "/name")
    @TestAnnoction(value = true)
    public void insertMattersave(@RequestParam("sid") Long sid, @RequestParam("name") String name,@RequestParam("number") Long number){
        Matter matter = matterService.queryMatterByName(name);
        Matter m = new Matter();
        if (matter==null) {
           m.setName(name);
           m.setEcode("abs");
           matterService.insertMatter(m);
        } else {
            if (mattersaveService.queryBySid(matter.getId(),sid)!=null) {
                mattersaveService.updateMattersave(sid,matter.getId(),number);
            }else {
                Mattersave mattersave = new Mattersave();
                mattersave.setNumber(number);
                mattersave.setSid(sid);
                mattersave.setMid(matter.getId());
                mattersaveService.insertMattersave(mattersave);
            }
        }
    }

    @PostMapping(value = "/id")
    @TestAnnoction(value = true)
    public void updateMattersaveBynumber(@RequestParam("sid") Long sid, @RequestParam("mid") Long mid,@RequestParam("number") Long number){
            mattersaveService.updateMattersaveBynumber(sid,mid,number);

    }




    @GetMapping(value = "/mid")
    @TestAnnoction(value = true)
    public List<Mattersave> queryMattersaveByMid(@RequestParam("mid") Long mid){
        return mattersaveService.queryMattersaveByMid(mid);
    }
    @DeleteMapping
    @TestAnnoction(value = true)
    @Transactional(rollbackFor = Exception.class)
    public void deleteMatterAndMattersave(@RequestParam("number") Long number){
        List<Mattersave> mattersaveList = mattersaveService.queryMattersaveByNumber(number);
        for (Mattersave mattersave:mattersaveList) {
            Long maId = mattersave.getId();
            Long mid = mattersave.getMid();
            matterService.deleteMatter(mid);
            mattersaveService.deleteMattersave(maId);
        }
    }
}
